package com.example.viewpager_demo;

import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity
{
    AutoScrollViewPager mViewPager;
    private final static int[] LEADING_IMAGE_RESOURCES = new int[]{R.drawable.s1,R.drawable.s2,R.drawable.s3,R.drawable.s1};
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //初始化控件
        initWidget();
    }

    private void initWidget()
    {
        mViewPager =  (AutoScrollViewPager) findViewById(R.id.vp_scroll);
        AutoScrollPagerAdapter adapter = new AutoScrollPagerAdapter(initViewList());
        mViewPager.setAdapter(adapter);

        //设置滚动的效果  ViewPager没有直接提供方法去改变滚动效果，必须通过java中反射去修改
        try
        {
            Field field = ViewPager.class.getDeclaredField("mScroller");
            field.setAccessible(true);
            AutoViewPagerScroller scroller = new AutoViewPagerScroller(this);
            field.set(mViewPager,scroller);
        } catch (NoSuchFieldException e)
        {
            e.printStackTrace();
        } catch (IllegalAccessException e)
        {
            e.printStackTrace();
        }


    }

    @Override
    protected void onResume()
    {
        super.onResume();
        //开始自动滚动
        mViewPager.startSlinding();
    }

    @Override
    protected void onStop()
    {
        super.onStop();
        mViewPager.stopSlinding();
    }

    //初始化ViewPager的视图
    private List<View> initViewList()
    {
        List<View> viewList = new ArrayList<View>();
        for (int i = 0; i < LEADING_IMAGE_RESOURCES.length; i++)
        {
            ImageView imageView = new ImageView(this);
            imageView.setImageResource(LEADING_IMAGE_RESOURCES[i]);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            viewList.add(imageView);
        }
        return viewList;
    }
}
